"use strict";

define(["angular", "app", "../models/User", "../services/socket"], function (angular, app) {
    app.controller("contactsController", function ($scope, User, socket) {
        User.getAll().then(function (data) {
            $scope.users = data;
        });
        var socketId;
        socket.on("connect", function () {
            socketId = socket.nsp + "#" + socket.id;
            socket.emit("getFocusList", {});
        });
        socket.on("focusList", function (data) {
            if (!angular.isArray($scope.users))
                return;            
            $scope.users.forEach(function (user) {
                for (var i = 0; i < data.length; i++) {
                    if (user.id === data[i].uid && data[i].id !== socketId) {
                        $scope.$apply(function () {
                            user.disabled = true;
                        });
                        return;
                    }                    
                }
                $scope.$apply(function () {
                    user.disabled = false;                    
                });
            });
        });
        socket.on("blur", function (data) {
            if (!angular.isArray($scope.users))
                return;
            for (var i = 0; i < $scope.users.length; i++) {
                if ($scope.users[i].id === data.id) {
                    $scope.$apply(function () {
                        angular.extend($scope.users[i], data);
                    });
                    return;
                }
            }
        });
        socket.on("created", function (data) {
            if (!angular.isArray($scope.users))
                return;
            $scope.$apply(function () {
                $scope.users.push(data);
            });            
        });
        $scope.focus = function () {
            if (!this.user.disabled) {
                socket.emit("focus", {
                    uid: this.user.id,
                });
            }
        };
        $scope.blur = function () {
            socket.emit("blur", this.user);
        };
        $scope.create = function () {
            socket.emit("create", {
                name: $scope.newUsername
            });
            $scope.newUsername = "";
        };
    });
});